// 全局变量
let cart = JSON.parse(localStorage.getItem('cart')) || [];

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 更新购物车数量
    updateCartCount();
    
    // 设置登录状态
    updateLoginStatus();
    
    // 购物车页逻辑
    if (window.location.pathname.includes('cart.html')) {
        // 加载购物车商品
        loadCartItems();
        
        // 更新购物车摘要
        updateCartSummary();
        
        // 去结算按钮事件
        document.getElementById('checkout-btn').addEventListener('click', function() {
            // 使用 authToken 判断登录状态
            if (!localStorage.getItem('authToken')) {
                localStorage.setItem('redirectAfterLogin', 'order.html');
                window.location.href = 'login.html';
                return;
            }
            window.location.href = 'order.html';
        });
    }
});

// 加载购物车商品
function loadCartItems() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const cartItems = document.getElementById('cart-items');
    cartItems.innerHTML = '';
    
    if (cart.length === 0) {
        cartItems.innerHTML = '<p>您的购物车是空的</p>';
        return;
    }
    
    cart.forEach(item => {
        const product = getProductById(item.id);
        if (product) {
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item';
            cartItem.innerHTML = `
                <div class="item-image">
                    <img src="${item.image}" alt="${item.name}">
                </div>
                <div class="item-details">
                    <h3>${item.name}</h3>
                    <p class="item-description">${product.description || '暂无描述'}</p>
                    <p class="item-spec">规格: ${product.spec || '暂无规格信息'}</p>
                    <div class="item-price">单价: ¥${item.price}</div>
                    <div class="item-quantity">
                        <label>数量:</label>
                        <input type="number" value="${item.quantity}" min="1" max="${product.stock || 99}" 
                            onchange="updateQuantity(${item.id}, this.value)">
                    </div>
                    <div class="item-total">小计: ¥${(item.price * item.quantity).toFixed(2)}</div>
                    <button class="remove-item" onclick="removeFromCart(${item.id})">移除</button>
                </div>
            `;
            cartItems.appendChild(cartItem);
        }
    });
}

// 更新商品数量
function updateQuantity(productId, quantity) {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const itemIndex = cart.findIndex(item => item.id === productId);
    
    if (itemIndex !== -1) {
        // 确保数量在合理范围内
        quantity = Math.max(1, Math.min(parseInt(quantity) || 1, 99));
        cart[itemIndex].quantity = quantity;
        localStorage.setItem('cart', JSON.stringify(cart));
        loadCartItems();
        updateCartSummary();
    }
}

// 从购物车移除商品
function removeFromCart(productId) {
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    cart = cart.filter(item => item.id !== productId);
    localStorage.setItem('cart', JSON.stringify(cart));
    loadCartItems();
    updateCartSummary();
    updateCartCount();
}

// 更新购物车摘要
function updateCartSummary() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
    const subtotal = cart.reduce((total, item) => total + (item.price * item.quantity), 0);
    const shipping = subtotal > 100 ? 0 : 10; // 满100免运费
    const total = subtotal + shipping;
    
    document.getElementById('total-items').textContent = totalItems;
    document.getElementById('subtotal').textContent = `¥${subtotal.toFixed(2)}`;
    document.getElementById('shipping').textContent = `¥${shipping.toFixed(2)}`;
    document.getElementById('total').textContent = `¥${total.toFixed(2)}`;
}

// 更新购物车数量
function updateCartCount() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const count = cart.reduce((total, item) => total + item.quantity, 0);
    document.getElementById('cart-count').textContent = count;
}

// 更新登录状态显示
function updateLoginStatus() {
    const loginLink = document.getElementById('login-link');
    const profileLink = document.querySelector('nav ul li a[href="profile.html"]');
    
    // 使用 authToken 判断登录状态
    if (localStorage.getItem('authToken')) {
        loginLink.textContent = '登出';
        loginLink.href = '#';
        loginLink.addEventListener('click', logout);
        if (profileLink) profileLink.style.display = 'block';
    } else {
        loginLink.textContent = '登录';
        loginLink.href = '#';
        loginLink.addEventListener('click', function(e) {
            e.preventDefault();
            localStorage.setItem('redirectAfterLogin', window.location.pathname);
            window.location.href = 'login.html';
        });
        if (profileLink) profileLink.style.display = 'none';
    }
}

// 登出功能
function logout() {
    // 移除认证令牌
    localStorage.removeItem('authToken');
    localStorage.removeItem('userInfo');
    
    // 更新登录链接文本
    updateLoginStatus();
    
    // 显示登出提示
    showToast('已成功登出');
    
    // 刷新页面
    setTimeout(() => {
        window.location.reload();
    }, 1500);
}

// 显示提示消息
function showToast(message) {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    
    // 添加到页面
    document.body.appendChild(toast);
    
    // 显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    // 3秒后隐藏
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}

// 获取商品信息
function getProductById(productId) {
    // 使用你的原始商品数据
    const products = [
        {
            id: 1,
            name: 'Macbook Air',
            price: 9999,
            description: '轻薄便携的笔记本电脑，适合日常办公和娱乐使用。',
            image: 'https://picsum.photos/seed/macbook/300/200',
            category: '电子产品',
            spec: 'M1芯片/8GB/256GB'
        },
        {
            id: 2,
            name: 'iphone16 pro',
            price: 14999,
            description: '最新款旗舰智能手机，拥有超强拍照能力和处理性能。',
            image: 'https://picsum.photos/seed/iphone/300/200',
            category: '电子产品',
            spec: '128GB/深空黑'
        },
        {
            id: 3,
            name: 'iphone16 promax',
            price: 24999,
            description: '大屏旗舰智能手机，适合追求极致体验的用户。',
            image: 'https://picsum.photos/seed/iphonepromax/300/200',
            category: '电子产品',
            spec: '256GB/金色'
        },
        {
            id: 4,
            name: 'ipone15 plus',
            price: 7999,
            description: '性价比高的智能手机，拥有大屏幕和长续航。',
            image: 'https://picsum.photos/seed/iphone15/300/200',
            category: '电子产品',
            spec: '128GB/蓝色'
        }
    ];
    
    return products.find(product => product.id === productId);
}